package com.zlw.rabbitmq.api.returnlistener;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

/**
 * @author Zhaoluowei
 * @version 1.0
 * @date 2019/12/23 23:52
 */
public class Produce {

    public static void main(String[] args) throws IOException, TimeoutException {
        //1.创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setVirtualHost("/");
        connectionFactory.setHost("39.100.250.122");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");


        //2. 通过连接工厂 创建连接。
        Connection connection = connectionFactory.newConnection();

        //3. 通过connection 创建channel
        Channel channel = connection.createChannel();
        String exchangeName = "test_return_exchange";
        String routingKey = "test.return.save";
        String routingKeyError = "abc.save";

        String msg = "测试 rabbitmq的 返回消息";
        //channel.basicPublish(exchangeName, routingKey, true, null, msg.getBytes());

        channel.basicPublish(exchangeName, routingKeyError, true, null, msg.getBytes());


        channel.addReturnListener(new ReturnListener() {
            @Override
            public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println(replyCode + " " + replyText + " " + exchange + " " + routingKey + "  " + new String(body));
            }
        });


    }


}
